<template>
  <div class="courseBox">
    <el-row class="title">
      <el-col :span="4">
        <span>课程文件</span>
      </el-col>
      <el-col v-if="progressHidden" :span="13" style="margin-top: 6px;">
        <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"/>
      </el-col>
      <el-col :span="2" :offset="2" style="float: right;">
        <el-upload
          v-if="!disable"
          :before-upload="handleBefore"
          :on-change="handleChange"
          :http-request="uploadFileEnclosure"
          :show-file-list="false"
          action=""
          class="upload-demo"
        >
          <el-button slot="trigger" type="primary">新增课件</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-table
      :data="enclosureTableData"
      :default-sort="{prop: 'typeIndex', order: 'ascending'}"
      border
      style="width: 100%;text-align:center;margin-top:20px;"
    >
      <el-table-column label="编号" align="center" width="100">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="课件名称" sortable prop="name" align="center" width="300"/>
      <el-table-column label="课件存储路径" sortable prop="fileUrl" align="center"/>
      <el-table-column label="课件上传时间" sortable prop="createTimeStr" align="center" width="200"/>
      <el-table-column v-if="!disable" label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteEnclosure(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :current-page="currentpage"
      :page-size="pagesize"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
  </div>
</template>
<script>
  import {getTenantId, getUserId, getUserName} from '@/utils/auth'
  import Pagination from '@/components/Pagination' // 分页组件
  import {addEnclosureFromVideo, delEnclosureById, getCreateUploadVideoUrl, getEnclosureList, getRefreshUploadVideoInfo, saveUsedRecord, upLoadFileToOss} from '@/api/subject/digitalAssets' // 数据接口
  import eventBus from '@/eventBus'

  export default {
    components: {
      Pagination
    },
    data() {
      return {
        courseFileTableData: [],
        disable: false,
        total: 0,
        currentpage: 1,
        pagesize: 5,
        enclosureTableData: [],
        enclosureFilterTableData: [],
        EduxcloudCourse: {},
        progressHidden: false,
        percentage: 0,
      }
    },
    created() {
      this.acceptWord();
    },
    methods: {
      // 上传之前
      handleBefore() {
      },
      // 上传封面
      handleChange(file) {
        this.file = file.raw
      },
      uploadFileEnclosure() {
        const type = this.file.name.substring(this.file.name.lastIndexOf('.') + 1);
        const name = this.file.name.substring(0, this.file.name.lastIndexOf('.'));
        const videoArr = ['AVI', 'MKV', 'MOV', 'MP4', 'TS', 'RMVB', 'WMV', 'XVID', 'X264', 'X265', 'MPG'];
        if (videoArr.indexOf(type.toLocaleUpperCase()) !== -1) {
          const userData = '{"Vod":{}} ';
          const uploader = this.createUploader();
          uploader.addFile(this.file, null, null, null, userData);
          uploader.startUpload()
        } else {
          setTimeout(() => {
            const fileForm = new FormData();
            fileForm.append('name', name);
            fileForm.append('type', type);
            fileForm.append('file', this.file);
            fileForm.append('assetsUnitId', this.EduxcloudCourse.id);
            fileForm.append('creator', getUserName());
            fileForm.append('tenantId', getTenantId());
            upLoadFileToOss(fileForm).then(res => {
              // this.getEnclosure(this.EduxcloudCourse.id);
              this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                duration: 2000
              })
            })
          }, 100)
        }
      },
      // 接收兄弟传值
      acceptWord() {
        eventBus.$on('acceptEduxcloudCourseId', (data) => {
          console.log('accept id:' + data);
          this.EduxcloudCourse.id = data
        })
      },
      handleSizeChange(val) {
        this.currentpage = 1;
        this.pagesize = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      handleCurrentChange(val) {
        this.currentpage = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
      },
      // 删除
      deleteEnclosure(row) {
        this.$confirm('确定要删除吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delEnclosureById(row.id, row.fileUrl).then(res => {
            this.getEnclosure(row.assetsId);
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      getEnclosure(id) {
        getEnclosureList(id).then(res => {
          this.enclosureTableData = res.data.items;
          this.enclosureFilterTableData = res.data.items;
          this.total = res.data.items.length
        })
      },
      createUploader() {
        /* eslint-disable */
        const _this = this;
        const uploader = new AliyunUpload.Vod({
          timeout: 60000,
          partSize: 1048576,
          parallel: 5,
          retryCount: 3,
          retryDuration: 2,
          region: '',
          userId: '1560516061941369',

          // 添加文件成功
          addFileSuccess: function (uploadInfo) {
            // 显示上传进度
            _this.progressHidden = true;
            console.log('addFileSuccess: ' + uploadInfo.file.name + ' uploadInfo.videoId: ' + uploadInfo.videoId)
          },
          // 开始上传
          onUploadstarted: function (uploadInfo) {
            console.log('uploadInfo.videoId:' + uploadInfo.videoId);
            // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
            // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
            // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
            // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
            // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
            // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
            if (uploadInfo.videoId) {
              // 如果videoId有值，根据videoId刷新上传凭证
              // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
              // var refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
              getRefreshUploadVideoInfo(uploadInfo.videoId).then(res => {
                const uploadAuth = res.UploadAuth;
                const uploadAddress = res.UploadAddress;
                const videoId = res.VideoId;
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              })
            } else {
              // var createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
              const title = uploadInfo.file.name.substring(0, uploadInfo.file.name.lastIndexOf('.'));
              const fileForm = new FormData();
              fileForm.append('title', title);
              fileForm.append('fileName', uploadInfo.file.name);
              getCreateUploadVideoUrl(fileForm).then(res => {

                const uploadAuth = res.data.result.UploadAuth;
                const uploadAddress = res.data.result.UploadAddress;
                const videoId = res.data.result.VideoId;
                console.log('uploadAuth' + uploadAuth + ',uploadAddress：' + uploadAddress + ',videoId：' + videoId);
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
              });
              console.log('onUploadStarted:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
            }
          },
          // 文件上传成功
          onUploadSucceed: function (uploadInfo) {
            console.log('onUploadSucceed: ' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object);
            const endpoint = uploadInfo.endpoint.split('//')[1];
            const url = 'https://' + uploadInfo.bucket + '.' + endpoint + '/' + uploadInfo.object; // URL
            const id = uploadInfo.videoId.trim();
            const name = uploadInfo.file.name.trim();
            const assetsId = _this.EduxcloudCourse.id;
            const fileForm = new FormData();
            _this.progressHidden = false;
            _this.percentage = 0;
            fileForm.append('url', url);
            fileForm.append('fileId', id);
            fileForm.append('fileName', name);
            fileForm.append('assetsUnitId', assetsId);
            fileForm.append('creator', getUserName());
            fileForm.append('tenantId', getTenantId());
            addEnclosureFromVideo(fileForm).then(res => {
              _this.getEnclosure(assetsId);
              _this.$notify({
                title: '成功',
                message: '文件上传成功',
                type: 'success',
                duration: 2000
              })
            })
          },
          // 文件上传失败
          onUploadFailed: function (uploadInfo, code, message) {
            console.log('onUploadFailed: file:' + uploadInfo.file.name + ',code:' + code + ', message:' + message);
            _this.$message.error('文件上传失败!')
          },
          // 取消文件上传
          onUploadCanceled: function (uploadInfo, code, message) {
            console.log('Canceled file: ' + uploadInfo.file.name + ', code: ' + code + ', message:' + message);
            _this.$message.warning('文件上传已暂停!')
          },
          // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
          onUploadProgress: function (uploadInfo, totalSize, progress) {
            console.log('onUploadProgress:file:' + uploadInfo.file.name + ', fileSize:' + totalSize + ', percent:' + Math.ceil(progress * 100) + '%');
            const progressPercent = Math.ceil(progress * 100);
            _this.percentage = progressPercent;
            if (progressPercent === 100) {
              const recordForm = new FormData();
              recordForm.append('size', totalSize);
              recordForm.append('userId', getUserId());
              saveUsedRecord(recordForm)
            }
            // $('.progress-bar').css('width', progressPercent + '%')
            // $('#status').text('文件上传中...')
          },
          // 上传凭证超时
          onUploadTokenExpired: function (uploadInfo) {
            // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
            // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
            // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
            _this.$message.error('文件上传超时!');
            getRefreshUploadVideoInfo(uploadInfo.videoId).then(res => {
              const uploadAuth = res.data.result.UploadAuth;
              uploader.resumeUploadWithAuth(uploadAuth);
              console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
            })
          },
          // 全部文件上传结束
          onUploadEnd: function (uploadInfo) {
            _this.$notify({title: '成功', message: '文件上传完毕!', type: 'success', duration: 2000});
            console.log('onUploadEnd: uploaded all the files')
          }
        });
        return uploader;
      }
    }
  }
</script>
<style lang="scss" scoped>
  .courseBox {
    .title {
      margin: 10px 0;

      span {
        font-size: 18px;
      }

      button {
        float: right;
        margin-top: -6px;
      }
    }
  }
</style>
